import {defineComponent, ref, onMounted, computed, h, onUnmounted} from 'vue';
import Pagination from '~/src/components/Pagination';
import Table from '~/src/components/table';
import { UserInfo } from '~/src/components/UserInfo';
import Style1080 from './1080.module.scss';
import Stylevedio from './vediotop.module.scss';
import {KEEP_VIDEO_TOP, ZFLX} from '~/src/config';
import {getyyqhlist, quhao, yjs,} from "@/api/his";
import { usePage,showConfirm,showMessage } from "@/utils/hooks";
import { useUserStore } from "@/store/modules/user";
import { QhType } from "@/api/typing";
import { closeLoading, showLoading } from "@/utils";
import { ElMessage, ElMessageBox } from "element-plus";
import router from "@/router";
import {tempStore} from "@/store/modules/temp";
import {XZLHFF} from '@/config/index'

export default defineComponent({
    setup() {
        const Style = KEEP_VIDEO_TOP ? Stylevedio : Style1080;
        const pageSize = ref(0);
        pageSize.value = KEEP_VIDEO_TOP ? 5 : 10;

        const tempstore = tempStore();
        // 表格表头（保持不变）
        const tableColumns = ref([
            {
                title: '就诊日期',
                dataIndex: 'JZRQ',
                align: "center" as "center",
                textalign: "left" as "left",
                cellStyle: { fontSize: '30px' },
                headerStyle: { fontSize: '30px', fontWeight: 'bold' as "bold" },
            },
            {
                title: '预约渠道',
                dataIndex: 'YYQD',
                align: "center" as "center",
                textalign: "left" as "left",
                cellStyle: { fontSize: '30px' },
                headerStyle: { fontSize: '30px', fontWeight: 'bold' as "bold"},
            },
            {
                title: '科室',
                dataIndex: 'KSMC',
                align: "center" as "center",
                textalign: "left" as "left",
                cellStyle: { fontSize: '30px' },
                headerStyle: { fontSize: '30px', width: '200px', fontWeight: 'bold' as "bold"},
            },
            {
                title: '医生',
                dataIndex: 'YSMC',
                align: "center" as "center",
                textalign: "left" as "left",
                cellStyle: { fontSize: '30px' },
                headerStyle: { fontSize: '30px', width: '100px', fontWeight: 'bold' as "bold"},
            },{
                title: '取号状态',
                dataIndex: 'QHZT',
                align: "center" as "center",
                textalign: "left" as "left",
                cellStyle: { fontSize: '30px'},
                headerStyle: { fontSize: '30px', fontWeight: 'bold' as "bold"},
            },{
                title: '操作',
                dataIndex: 'CZ',
                align: "center" as "center",
                cellStyle: { fontSize: '30px' },
                headerStyle: { fontSize: '30px', fontWeight: 'bold' as "bold"},
                render: (record: QhType) => (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '5px', }}>
                        {/* 取号按钮 */}
                        <button
                            style={{
                                width: '120px',
                                fontSize: '20px',
                                backgroundColor: record.status !== 0 ? '#cccccc' : '#4CAF50',
                                color: 'white',
                                border: 'none',
                                borderRadius: '8px',
                                cursor: 'pointer',
                            }}
                            disabled={record.status !== 0}
                            onClick={() => handleTakeNumber(record)}
                        >
                            <span style={{ fontSize: '25px' }}>取号</span>
                        </button>
                        {/* 取消预约按钮 */}
                        <button
                            style={{
                                fontSize: '20px',
                                backgroundColor: record.status !== 0 ? '#cccccc' : '#f44336',
                                color: 'white',
                                border: 'none',
                                borderRadius: '8px',
                                cursor: 'pointer',
                                width: '120px',
                            }}
                            disabled={record.status !== 0}
                            onClick={() => handleCancelReservation(record)}
                        >
                            <span style={{ fontSize: '25px' }}>取消预约</span>
                        </button>
                    </div>
                ),
            },
        ]);

        onUnmounted(() => {
            ElMessageBox.close();
        });
        // 取号按钮点击事件
        const handleTakeNumber = async (record: QhType) => {
            const isConfirm = await showConfirm('提示', `确定要取号操作吗？`, 'warning');
            if (isConfirm) {
                tempstore.setqh(record) // 保存取号信息
                console.log(`取号${record.id} - 就诊日期: ${record.JZRQ}, 科室: ${record.KSMC}, 医生: ${record.YSMC}`);
                //先诊疗 后付费
                if (XZLHFF){
                    let res = await quhao({
                        id:tempstore.qh?.id,
                        type:'true'
                    });
                    console.log('先诊疗后付费，取号成功')
                    router.push({path:'lqpt'});
                // 先付费 后诊疗
                }else {
                    // 无医保  全自费
                    if (ZFLX){
                        // 1.预结算
                        let res =await yjs({
                            id:tempstore.qh?.id,
                            xzpayType:'1', // 0医保 1 自费
                        })
                        tempstore.setyjsItemInfo({
                            zfje:res.rows.zfje,
                            ybje:res.rows.ybje,
                            zje:res.rows.zje,
                            lsh:res.rows.lsh,
                            orderNo:res.rows.orderNo,
                            goType:res.rows.type,
                        })
                        router.push({path:'/smt'})
                    // 医保+自费 /自费
                    }else {
                        router.push({
                            path: "/selectPayType",
                            query:{}
                        })
                    }
                }
            } else {
                console.log(`已取消取号操作`);
                showMessage('已取消取号操作！', 'info');
            }
        };

        // 取消预约按钮点击事件
        const handleCancelReservation = async (record: QhType) => {
            const isConfirm = await showConfirm('提示', `确定要取消预约吗？`, 'warning');
            if (isConfirm) {
                console.log(`取消预约${record.id} - 就诊日期: ${record.JZRQ}, 科室: ${record.KSMC}, 医生: ${record.YSMC}`);
                showLoading();
                let res = await quhao({
                    id:tempstore.qh?.id,
                    type:'false'
                });
                closeLoading();
                showMessage('取消预约成功！', 'success');
                getyyqhData();
            } else {
                showMessage('已取消取消预约操作！', 'info');
            }
        };

        // 表格数据相关（保持不变）
        const showDatas = ref();
        const handlePageChange = (Datas: any) => {
            showDatas.value = Datas;
        };


        const tableData = ref<QhType[]>([]);
        async function getyyqhData() {
                showLoading();
                let res = await getyyqhlist({});
                tableData.value = res.rows!;
                //如果res.rows里item.status等于0的put进去一个QHZT列，值为待取号，等于1已取号，2已取消
                res.rows!.forEach((item: QhType) => {
                    item.QHZT = item.status === 0 ? '待取号' : item.status === 1 ? '已取号' : '已取消';
                })
                closeLoading();
        }
        getyyqhData();
        return () => (
            <>
                <div class={Style.top}>
                    <UserInfo ></UserInfo>
                    <div class={Style.container_mar} >
                        <div class={Style.body}>
                            <Table
                                columns={tableColumns.value}
                                data={showDatas.value}
                                tableStyle={{}}
                                containerStyle={{ width: "97%", height: "100%" }}
                            ></Table>
                        </div>
                        <Pagination
                            style={{ margin: '0 63px' }}
                            pageSize={pageSize.value}
                            Data={tableData.value}
                            onPageChange={handlePageChange}
                        ></Pagination>
                    </div>
                </div>

            </>
        );
    }
})
